import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:kasax/commons/commons.dart';
import 'package:kasax_demos2/entry/entrys.dart';
import 'package:kasax_demos2/providers/data_providers.dart';

/// 技术实现方案参考:FutureBuilder
/// typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot);
class PostsListWidget extends StatefulWidget {
  // 使用builder让用户在创建该对象的时候，构建自定义的子view
  final AsyncWidgetBuilder<List<Posts>> builder;

  const PostsListWidget(this.builder, {Key? key}) : super(key: key);

  @override
  _PostsListWidgetState createState() => _PostsListWidgetState();
}

class _PostsListWidgetState extends State<PostsListWidget> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      builder: (BuildContext context, AsyncSnapshot<List<Posts>> snapshot) {
        return buildPageContent(snapshot);
      },
      future: DataProvider.getInstance().fetchAllPostsWithDio(),
    );
  }

  buildPageContent(AsyncSnapshot<List<Posts>> asyncsnapshot) {
    var connectionState = asyncsnapshot.connectionState;
    log("connectionState: $connectionState");
    if (connectionState == ConnectionState.waiting) {
      return buildLoadingWidget();
    } else if (connectionState == ConnectionState.done) {
      return (asyncsnapshot.data == null || asyncsnapshot.data!.isEmpty)
          ? buildLoadingWidget()
          : widget.builder.call(context, asyncsnapshot);
    }
  }

  /// 考虑到通用，这里去除
  CustomScrollView buildCustomScrollView(AsyncSnapshot<List<Posts>> asyncsnapshot) {
    return CustomScrollView(
      slivers: [
        // 显示在安全区域
        SliverSafeArea(
            // 添加内边距
            sliver: SliverPadding(
          padding: EdgeInsets.all(8.0),
          // 让用户使用自己的控件
          sliver: widget.builder.call(context, asyncsnapshot),
        ))
      ],
    );
  }
}
